package com.xiaolun.netty.codec;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * 方法1
 * public class NettyServerHandler extends ChannelInboundHandlerAdapter {
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<StudentPOJO.Student> {
	//读取数据实际(这里我们可以读取客户端发送的消息)
    /*
    1. ChannelHandlerContext ctx:上下文对象, 含有 管道pipeline , 通道channel, 地址
    2. Object msg: 就是客户端发送的数据 默认Object
     */
	@Override
	public void channelRead0(ChannelHandlerContext ctx, StudentPOJO.Student msg) throws Exception {
		//读取从客户端发送的StudentPojo.Student
		System.out.println("客户端发送的数据 id=" + msg.getId() + " 名字=" + msg.getName());
	}

	/**
	 * 方法2
	 *
	 * @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	 * //读取从客户端发送的StudentPojo.Student
	 * StudentPOJO.Student student = (StudentPOJO.Student) msg;
	 * System.out.println("客户端发送的数据 id=" + student.getId() + " 名字=" + student.getName());
	 * }
	 */

	//数据读取完毕
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(>^ω^<)喵1", CharsetUtil.UTF_8));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}
}
